package com.emep.emeptime.controller;


import com.emep.emeptime.model.ApiData;
import com.emep.emeptime.service.AreaAqiMoniterService;
import com.emep.emeptime.utils.DateUtils;
import com.emep.emeptime.utils.GsonUtils;
import com.emep.emeptime.utils.Quantity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author wangcc
 * @version V1.0
 * @Description: 监测和城市数据定时器
 * @date 2018/3/30  13:51
 */
@Component
public class AreaAqiMoniterController {

    private static final Logger log = LoggerFactory.getLogger(AreaAqiMoniterController.class);

    @Autowired
    private AreaAqiMoniterService areaAqiMoniterService;


    //@Scheduled(cron="0 0/15 * * * ?")
    @Scheduled(cron="0 50 0/1 * * ?")
    public void getDatasync(){
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)//写入超时
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build();
            Request request = new Request.Builder()
                    .url(Quantity.HTTP)
                    .build();
            Response response = null;
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                    log.info("***************** 【监控数据HTTP 请求成功】 请求状态:=={},时间:=={}", response.code(),DateUtils.getNowTime());
                    List<ApiData> apiData =new Gson().fromJson(response.body().string(), new TypeToken<List<ApiData>>() {}.getType());
                    areaAqiMoniterService.save(apiData);
                    }else {
                log.error("***************** 【监控数据HTTP 请求失败！！！】 请求状态:=={},时间:=={}", response.code(),DateUtils.getNowTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
       }
    }
}

